package com.yoomiito.app.widget;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yoomiito.app.R;
import com.yoomiito.app.model.gift.GiftType;
import com.yoomiito.app.utils.DensityUtil;

import java.util.ArrayList;
import java.util.List;

public class SortPopupWindow {

    private ImageView iv;
    private Context mContext;
    private PopupWindow mPopupWindow;
    private int triangleWidth;
    private int triangleHeight;
    private int radius;
    private int mPopupWindowWidth;
    private int mPopupWindowHeight;
    private int mRawX;
    private int mRawY;
    private View anchorView;
    private int mScreenWidth;
    private int mScreenHeight;
    private View view;
    private RecyclerView rcy;
    List<GiftType> types = new ArrayList<>();
    private RcyAdapter rcyAdapter;
    private OnSortSelectListener mOnSortSelectListener;

    public SortPopupWindow(Context context) {
        mContext = context;
        mScreenWidth = getScreenWidth();
        mScreenHeight = getScreenHeight();
        radius = DensityUtil.dp2px(8);
        triangleWidth = DensityUtil.dp2px(16);
        triangleHeight = DensityUtil.dp2px(8);
    }

    public void init() {
        view = LayoutInflater.from(mContext).inflate(R.layout.item_sort_pop, null);
        iv = view.findViewById(R.id.item_sort_s);
        rcy = view.findViewById(R.id.item_sore_pop_rcy);

        initRcy();
        initPopupWindow();
    }

    private void initRcy() {
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 3);
        rcy.setLayoutManager(layoutManager);
        rcyAdapter = new RcyAdapter(types);
        rcy.setAdapter(rcyAdapter);
    }

    private void initPopupWindow() {
        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        mPopupWindowWidth = mPopupWindow.getContentView().getMeasuredWidth();
    }

    public void setData(List<GiftType> types) {
        this.types.clear();
        if (types!=null){
            this.types.addAll(types);
        }
        rcyAdapter.notifyDataSetChanged();
    }

    public void setAnchorView(View anchorView) {
        this.anchorView = anchorView;
        anchorView.setOnTouchListener((v, event) -> {
            mRawX = (int) event.getRawX();
            mRawY = (int) event.getRawY();
            return false;
        });
    }

    public void show() {
        mPopupWindow.showAsDropDown(anchorView);
    }

    private void indicatorTranslationX(int marginLeftIndicator, int marginRightIndicator) {
        int translationX = (mScreenWidth - mRawX - DensityUtil.dp2px(12));
        iv.setTranslationX(-translationX);
    }

    /**
     * 显示Pop在view的右下方
     */
    public void showPopWindow(View view) {
        int marginLeftIndicator = mRawX;
        int marginRightIndicator = mScreenWidth - marginLeftIndicator;
        indicatorTranslationX(marginLeftIndicator, marginRightIndicator);
        int[] point = {0, 0};
        anchorView.getLocationOnScreen(point);
        mPopupWindow.showAtLocation(anchorView, Gravity.RIGHT | Gravity.TOP, DensityUtil.dp2px(12), point[1] + anchorView.getHeight());
    }


    public void showPopWindow(View parent, int gravity, int x, int y) {
        mPopupWindow.showAtLocation(parent, gravity, x, y);
    }

    public void dismissPopWindow() {
        mPopupWindow.dismiss();
    }

    public boolean isShowing() {
        return mPopupWindow.isShowing();
    }

    private int getViewWidth(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        return view.getMeasuredWidth();
    }

    private int getViewHeight(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        return view.getMeasuredHeight();
    }

    private int getScreenWidth() {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    private int getScreenHeight() {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    class RcyAdapter extends BaseQuickAdapter<GiftType, BaseViewHolder> {

        public RcyAdapter(@Nullable List<GiftType> data) {
            super(R.layout.item_sort_tv, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, GiftType item) {
            TextView tv = helper.getView(R.id.item_sort_tv);
            tv.setText(item.getGift_name());
            tv.setSelected(item.isSelected());
            tv.setOnClickListener(v -> {
                        changeTv(helper.getLayoutPosition());
                        if (mOnSortSelectListener != null) {
                            mOnSortSelectListener.onSelect(types.get(helper.getLayoutPosition()));
                        }
                        if (isShowing()){
                            dismissPopWindow();
                        }
                    }
            );
        }

        private void changeTv(int position) {
            for (int i = 0; i < types.size(); i++) {
                GiftType type = types.get(i);
                if (i == position) {
                    type.setSelected(true);
                } else {
                    if (type.isSelected()) {
                        type.setSelected(false);
                    }
                }
            }
            notifyDataSetChanged();
        }

    }

    public void setOnSortSelectListener(OnSortSelectListener onSortSelectListener) {
        mOnSortSelectListener = onSortSelectListener;
    }

    public interface OnSortSelectListener {
        void onSelect(GiftType giftType);
    }
}
